package cn.bearspark.api.service.main.impl;

import cn.bearspark.api.service.main.DanmuService;
import cn.bearspark.api.vo.main.danmu.ListDanmuVO;
import cn.bearspark.api.vo.main.danmu.SendDanmuVO;
import cn.bearspark.common.util.ConvertBeanUtil;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author f
 */
@Service
public class DanmuServiceImpl implements DanmuService {

    private Long idGenerator = 1L;
    private final Map<Long, List<DanmuPO>> mapper = new HashMap<>();

    @Data
    public static class DanmuPO {
        /**
         * 弹幕的 id
         */
        private Long danmuId;
        /**
         * 弹幕所属的视频的 id TODO 应该还有发送弹幕的 userId
         */
        private Long videoId;
        /**
         * 弹幕的文本
         */
        private String text;
        /**
         * 弹幕发送的时刻，单位：s
         */
        private Integer time;
        /**
         * 弹幕的模式
         *
         * @see cn.bearspark.api.controller.main.DanmuController.DanmuModeEnum
         */
        private Integer mode;
        /**
         * 弹幕的颜色
         */
        private String color;
        /**
         * 弹幕是否有边框
         */
        private Boolean border;
    }

    @Override
    public void sendDanmu(SendDanmuVO sendDanmuVO) {
        DanmuPO danmuPO = ConvertBeanUtil.convert(sendDanmuVO, DanmuPO.class);
        danmuPO.setDanmuId(idGenerator++);
        mapper.computeIfAbsent(danmuPO.getVideoId(), k -> new ArrayList<>()).add(danmuPO);
    }

    @Override
    public List<ListDanmuVO> listDanmu(long videoId) {
        Random random = new Random();
        List<DanmuPO> danmuPOList = mapper.get(videoId);
        if (danmuPOList == null) {
            return Collections.emptyList();
        }
        return danmuPOList.stream().map(danmuPO -> {
            ListDanmuVO listDanmuVO = ConvertBeanUtil.convert(danmuPO, ListDanmuVO.class);
            listDanmuVO.setBorder(random.nextBoolean());
            return listDanmuVO;
        }).toList();
    }
}
